package org.infodavid.common.impl.tasks;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.infodavid.common.util.AbstractProcessor;
import org.infodavid.common.util.HelperUtil;
import org.infodavid.common.util.IVisitor;
import org.infodavid.common.util.IVisitor.IResult;

/**
 * The Class AbstractTaskProcessor.
 */
public abstract class AbstractTaskProcessor extends AbstractProcessor {

  /** The Constant log. */
  private static final Log LOGGER = LogFactory.getLog(AbstractTaskProcessor.class);

  /**
   * Execute.
   * @param task the task
   * @param data the data
   * @param <I> the input type
   * @param <O> the output type
   * @throws Throwable the error
   */
  protected <I extends Object,O extends Object> IResult<O> execute(final IVisitor<I,O> task,
      final I data) throws Throwable {
    LOGGER.info("Processing task: " + task);

    IResult<O> result = null;

    try {
      result = HelperUtil.getInstance().execute(task, data, getRetryCount(), getRetryPeriod());

      LOGGER.info("Task completed");
    }
    catch (final Exception e) {
      if (isFailOnError()) {
        throw e;
      }

      LOGGER.error("An error occurs while processing task", e);
    }

    return result;
  }
}
